package org.monkey.socket.plugin.config;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.monkey.socket.plugin.entity.WebSocketProperties;
import org.monkey.socket.plugin.handler.NioWebSocketHandler;

public class NioWebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {

  private WebSocketProperties webSocketProperties;
  private NioWebSocketHandler nioWebSocketHandler;

  public NioWebSocketChannelInitializer(
      WebSocketProperties webSocketProperties,
      NioWebSocketHandler nioWebSocketHandler) {
    this.webSocketProperties = webSocketProperties;
    this.nioWebSocketHandler = nioWebSocketHandler;
  }

  @Override
  protected void initChannel(SocketChannel socketChannel) {
    socketChannel.pipeline()
        .addLast(new HttpServerCodec())
        .addLast(new ChunkedWriteHandler())
        .addLast(new HttpObjectAggregator(65536))
        .addLast(nioWebSocketHandler)
        .addLast(
            new WebSocketServerProtocolHandler(webSocketProperties.getPath(), null, true, 65536));
  }
}
